package ynu.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import ynu.edu.entity.ModelConfig;
import ynu.edu.mapper.ModelConfigMapper;
import ynu.edu.service.ModelConfigService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 模型配置服务实现类
 */
@Service
public class ModelConfigServiceImpl implements ModelConfigService {

    @Resource
    private ModelConfigMapper modelConfigMapper;

    @Override
    public ModelConfig getModelConfig(String modelName) {
        if (modelName == null || modelName.trim().isEmpty()) {
            return getDefaultModel();
        }
        
        QueryWrapper<ModelConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("model_name", modelName)
                   .eq("enabled", true);
        
        return modelConfigMapper.selectOne(queryWrapper);
    }

    @Override
    public ModelConfig getDefaultModel() {
        return getModelConfig("text2img_normal");
    }

    @Override
    public List<ModelConfig> getEnabledModels() {
        QueryWrapper<ModelConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enabled", true)
                   .orderByAsc("id");
        
        return modelConfigMapper.selectList(queryWrapper);
    }

    @Override
    public List<ModelConfig> getText2ImgModels() {
        QueryWrapper<ModelConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enabled", true)
                   .and(wrapper -> wrapper.like("model_name", "text2img_"))
                   .orderByAsc("id");
        
        return modelConfigMapper.selectList(queryWrapper);
    }

    @Override
    public List<ModelConfig> getImg2ImgModels() {
        QueryWrapper<ModelConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enabled", true)
                   .and(wrapper -> wrapper.like("model_name", "img2img_"))
                   .orderByAsc("id");
        
        return modelConfigMapper.selectList(queryWrapper);
    }

    @Override
    public boolean existsModel(String modelName) {
        if (modelName == null || modelName.trim().isEmpty()) {
            return false;
        }
        
        QueryWrapper<ModelConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("model_name", modelName)
                   .eq("enabled", true);
        
        return modelConfigMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public ModelConfig getModelForParams(String modelName) {
        // 先尝试获取指定的模型
        ModelConfig model = getModelConfig(modelName);
        
        // 如果模型不存在，返回默认模型
        if (model == null) {
            return getDefaultModel();
        }
        
        return model;
    }
} 